package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {
    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    public String getVideoFollowUserKey(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }

    @Override
    public String saveVideo(Video video) {
        try {
            //校验
            if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())) {
                return null;
            }
            //设置id
            video.setId(ObjectId.get());
            video.setVid(idService.createAutoId(IdType.VIDEO));
            //发布时间
            video.setCreated(System.currentTimeMillis());
            //保存到Mongodb中
            mongoTemplate.save(video);
            return video.getId().toHexString();
        } catch (Exception e) {
            log.error("小视频发布失败~ video = " + video, e);
        }
        return null;
    }

    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //从redis中获取推荐视频的数据
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisData = redisTemplate.opsForValue().get(redisKey);
        List<Long> vids = new ArrayList<>();
        int recommendCount = 0;
        if (StrUtil.isNotEmpty(redisData)) {
            //手动分页查询数据
            List<String> vidList = StrUtil.split(redisData, ',');
            //计算分页
            //[0, 10]
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int start = startEnd[0];
            int end = Math.min(startEnd[1], vidList.size());
            for (int i = start; i < end; i++) {
                vids.add(Long.valueOf(vidList.get(i)));
            }
            recommendCount = vidList.size();
        }
        List<Video> videos = new ArrayList<>();
        if (CollUtil.isNotEmpty(vids)) {
            //根据vid查询对应的视频数据了
            Query query = Query.query(Criteria.where("vid").in(vids));
            videos = mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videos);
            if (vids.size() == pageSize) {
                return pageInfo;
            }
        }
        //没有推荐或前面推荐已经查询完毕，查询系统的视频数据
        //计算前面的推荐视频页数
        int totalPage = PageUtil.totalPage(recommendCount, pageSize);
        if (page == totalPage) {
            page++;
            pageSize = pageSize - vids.size();
        }
        PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Video> systemvideos = mongoTemplate.find(query, Video.class);
        for (Video systemvideo : systemvideos) {
            videos.add(systemvideo);
        }
        pageInfo.setRecords(videos);
        return pageInfo;
    }

    @Override
    public Video queryVideoById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        try {
            if (isFollowUser(userId, followUserId)) {
                return false;
            }
            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());
            mongoTemplate.save(followUser);
            //需要将用户的关注列表，保存到redis中，方便后续的查询
            String redisKey = getVideoFollowUserKey(userId);
            //使用redis的hash结构
            String hashKey = String.valueOf(followUserId);
            //保存数据到redis
            redisTemplate.opsForHash().put(redisKey, hashKey, "1");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        try {
            if (!isFollowUser(userId, followUserId)) {
                return false;
            }
            //取消关注，删除关注数据即可
            Query query = Query.query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
            FollowUser followUser = mongoTemplate.findOne(query, FollowUser.class);
            DeleteResult deleteResult = mongoTemplate.remove(followUser);

            //同时删除redis中的数据
            if (deleteResult.getDeletedCount() > 0) {
                String redisKey = getVideoFollowUserKey(userId);
                String hashKey = String.valueOf(followUserId);
                redisTemplate.opsForHash().delete(redisKey, hashKey);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(followUserId);
        return redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }
}
